package q592_fractionAddition;

public class Solution {
    /*
    再循环内部 每次读取一个新分数时 就利用合并的方式合并到当前的分数之中
    因为数字可能很大 所以使用long来表示分子分母
     */
    public String fractionAddition(String expression) {
        long s = 0, m = 1;
        int index = 0, n = expression.length();
        while (index < n) {
            long sign = 1, s1 = 0;
            if (expression.charAt(index) == '-' || expression.charAt(index) == '+') {
                sign = expression.charAt(index) == '-' ? -1 : 1;
                index++;
            }
            // 合并一个新分子分母
            while (index < n && Character.isDigit(expression.charAt(index))) {
                s1 = s1 * 10 + expression.charAt(index) - '0';
                ++index;
            }
            s1 *= sign;
            // 跳过中间除号
            ++index;

            long m1 = 0;
            while (index < n && Character.isDigit(expression.charAt(index))) {
                m1 = m1 * 10 + expression.charAt(index) - '0';
                ++index;
            }
            s = s * m1 + s1 * m;
            m *= m1;
        }


        if (s == 0) {
            return "0/1";
        }
        long g = gcd(Math.abs(s), m); // 获取最大公约数
        return s / g + "/" + m / g;

    }

    public long gcd(long a, long b) {
        return b == 0 ? a : gcd(b, a % b);
    }

}
